//
//  TextWebViewController.m
//  bridging_js
//
//  Created by cyptt on 2021/9/2.
//

#import "TextWebViewController.h"
#import <Photos/Photos.h>

@interface TextWebViewController ()

@end

@implementation TextWebViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    NSString * file;
    BOOL videoCompatible = UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(file);
    //检查视频能否保存至相册
    if (videoCompatible) {
        UISaveVideoAtPathToSavedPhotosAlbum(file, self,
    @selector(video:didFinishSavingWithError:contextInfo:), nil);
    } else {
        NSLog(@"该视频无法保存至相册");
    }
//    PHPhotoLibrary * lib = [PHPhotoLibrary sharedPhotoLibrary];
//    [lib performChanges:^{
//        NSURL * url ;
//        PHAssetChangeRequest *createAssetRequest = [PHAssetChangeRequest creationRequestForAssetFromVideoAtFileURL:url];
//               // 请求编辑这个相簿。
//              PHAssetCollectionChangeRequest *albumChangeRequest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:album];
//               // 得到一个新的资源的占位对象并添加它到相簿编辑请求中。
//              PHObjectPlaceholder *assetPlaceholder = [createAssetRequest placeholderForCreatedAsset];
//              [albumChangeRequest addAssets:@[ assetPlaceholder ]];
//
//        } completionHandler:^(BOOL success, NSError * _Nullable error) {
//
//        }];

    
}
- (PHAssetCollectionChangeRequest *)getCurrentPhotoCollectionWithAlbumName:(NSString *)albumName {
    // 1. 创建搜索集合
    PHFetchResult *result = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    
    // 2. 遍历搜索集合并取出对应的相册，返回当前的相册changeRequest
    for (PHAssetCollection *assetCollection in result) {
        if ([assetCollection.localizedTitle containsString:albumName]) {
            PHAssetCollectionChangeRequest *collectionRuquest = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:assetCollection];
            return collectionRuquest;
        }
    }
    
    // 3. 如果不存在，创建一个名字为albumName的相册changeRequest
    PHAssetCollectionChangeRequest *collectionRequest = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:albumName];
    return collectionRequest;
}

- (void)video:(NSString *)videoPath didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo {
    if (error) {
        NSLog(@"保存视频失败：%@", error);
    } else {
        NSLog(@"保存视频成功");
    }
}

@end
